package com.lintf.batch.api;

import com.lintf.batch.domain.Student;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ author lintf
 * @ system Mac
 * @ data 2025/8/15
 * @ package_name com.lintf.batch.api
 * @ project_name my-diy-project
 * @ desc
 */
public class ThirdPartyStudentApi {

    public static final int TOTAL_RECORDS = 100000;
    public static final int SIMULATE_DELAY = 50;
    public static final double ERROR_RATE = 0.1;

    /**
     * 获取指定页码的学生数据
     *
     * @param page     页码（从0开始）
     * @param pageSize 每页数据量
     * @return 学生数据列表
     */
    public static List<Student> fetchStudentsByBatch(int page, int pageSize) {
        try {
            Thread.sleep(SIMULATE_DELAY);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        int startIndex = page * pageSize;
        int endIndex = Math.min(startIndex + pageSize, TOTAL_RECORDS);

        if (endIndex <= startIndex) {
            return new ArrayList<>();
        }

        // 取消错误模拟，确保处理所有数据
        // if (Math.random() < ERROR_RATE) {
        //     throw new RuntimeException("第三方API异常: 第" + page + "页数据获取失败");
        // }

        List<Student> students = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            students.add(new Student("ID-" + i, "学生" + i, 18 + i % 5, "班级" + (i % 10)));
        }

        return students;
    }

    /**
     * 获取指定页码的学生数据
     *
     * @param page     页码（从0开始）
     * @param pageSize 每页数据量
     * @return 学生数据列表
     */
    public static List<Student> fetchStudentsByManual(int page, int pageSize) {
        try {
            Thread.sleep(SIMULATE_DELAY);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        int startIndex = page * pageSize;
        int endIndex = Math.min(startIndex + pageSize, TOTAL_RECORDS);

        if (endIndex <= startIndex) {
            return new ArrayList<>();
        }

        // 取消错误模拟，确保处理所有数据
        // if (Math.random() < ERROR_RATE) {
        //     throw new RuntimeException("第三方API异常: 第" + page + "页数据获取失败");
        // }

        List<Student> students = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            String studentId = "ID-" + i;
            String studentName = "学生" + i;
            int age = 18 + i % 5;
            String className = "班级" + (i % 10);
            Date date = new Date();
            students.add(new Student(studentId, studentName, age, className, date));
        }

        return students;
    }

}
